package com.xuecheng.media.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.*;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mapper.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalTime;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author HuangYuwu
 * @since 2022-09-12
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;

    /**
     * 获取阿里云上传token
     *
     * @param vodUploadDto
     * @return
     */
    @Override
    public ResponseResult vodTokenMedia(VodUploadDto vodUploadDto) throws Exception {
        if (StrUtil.isBlank(vodUploadDto.getTitle()) || StrUtil.isBlank(vodUploadDto.getFileName())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        CreateUploadVideoResponse videoResponse = vodTemplate.createUploadVideo(vodUploadDto.getTitle(), vodUploadDto.getFileName());
        VodUploadVo vodUploadVo = BeanHelper.copyProperties(videoResponse, VodUploadVo.class);
        vodUploadVo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vodUploadVo);
    }

    /**
     * 刷新阿里云上传token
     *
     * @param videoId
     * @return
     */
    @Override
    public ResponseResult refreshvodTokenMedia(String videoId) throws Exception {
        RefreshUploadVideoResponse videoResponse = vodTemplate.refreshUploadVideo(videoId);
        VodUploadVo vodUploadVo = BeanHelper.copyProperties(videoResponse, VodUploadVo.class);
        vodUploadVo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vodUploadVo);
    }

    /**
     * 保存媒资信息
     *
     * @param mediaDto
     * @return
     */
    @Override
    public ResponseResult saveMedia(MediaDto mediaDto) throws Exception {
        if (StrUtil.isBlank(mediaDto.getFilename()) || StrUtil.isBlank(mediaDto.getFileId())) {
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        Media media = BeanHelper.copyProperties(mediaDto, Media.class);
        AuthInfo authInfo = AuthInfoHolder.getAuthInfo();
        BeanUtils.copyProperties(authInfo, media);
        media.setUsername(authInfo.getUserName());
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);
        media.setCreateDate(DateUtil.date());

        GetPlayInfoResponse response = vodTemplate.getPlayInfo(mediaDto.getFileId());
        GetPlayInfoResponse.PlayInfo playInfo = response.getPlayInfoList().get(0);
        //获取视频时长和播放地址
        String duration = playInfo.getDuration();
        String playURL = playInfo.getPlayURL();
        // 将字符串转float 转 long
        Float f = Float.parseFloat(duration);
        // 91秒 -> 01:31
        String time = LocalTime.MIN.plus(Duration.ofMinutes(f.longValue())).toString();
        media.setUrl(playURL);
        media.setTimelength(time);
        this.save(media);
        return ResponseResult.okResult();
    }

    /**
     * 分页查询媒资信息
     * @param pageRequest
     * @param mediaQueryDto
     * @return
     */
    @Override
    public ResponseResult findMedia(PageRequest pageRequest, MediaQueryDto mediaQueryDto) {
        Page<Media>mediaVoPage=new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
        LambdaQueryWrapper<Media>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(mediaQueryDto.getFilename()),Media::getFilename,mediaQueryDto.getFilename());
        queryWrapper.eq(StrUtil.isNotBlank(mediaQueryDto.getAuditStatus()),Media::getAuditStatus,mediaQueryDto.getAuditStatus());
        queryWrapper.eq(StrUtil.isNotBlank(mediaQueryDto.getType()),Media::getType,mediaQueryDto.getType());
        mediaVoPage= this.page(mediaVoPage, queryWrapper);

        List<Media> mediaList = mediaVoPage.getRecords();
        List<MediaVo> mediaVoList = BeanHelper.copyWithCollection(mediaList, MediaVo.class);
        return PageResponseResult.okResult(mediaVoPage.getTotal(),mediaVoList);
    }

    /**
     * 预览媒资消息
     * @param mediaId
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult previewMedia(Long mediaId) throws Exception {
        Media media = this.getById(mediaId);
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        return ResponseResult.okResult(playURL);
    }

    /**
     * 根据id删除媒资信息
     * @param mediaId
     * @return
     */
    @Override
    public ResponseResult deleteMedia(Long mediaId){
        Media media=this.getById(mediaId);
        //审核通过代表可能已被他人绑定课程，故而不可移除
        if (media.getAuditStatus().equals(MediaConstants.AUDIT_PASTED_STATUS)){
            throw new BusinessException(ErrorCode.ERROR);
        }
        try {
            vodTemplate.deleteVideo(media.getFileId());
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        boolean remove = this.removeById(mediaId);
        if (!remove){
            throw new BusinessException(ErrorCode.ERROR);
        }
        return ResponseResult.okResult();
    }

    /**
     * 审核媒资
     * @param mediaAuditDto
     * @return
     */
    @Override
    public ResponseResult auditMedia(MediaAuditDto mediaAuditDto) {
        Media media = BeanHelper.copyProperties(mediaAuditDto, Media.class);
        this.updateById(media);
        return ResponseResult.okResult();
    }

    /**
     * 根据id查询媒资信息
     * @param mediaId
     * @return
     * @throws Exception
     */
    @Override
    public ResponseResult findMediaById(Long mediaId) throws Exception {
        Media media = this.getById(mediaId);
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        media.setUrl(playURL);
        MediaVo mediaVo = BeanHelper.copyProperties(media, MediaVo.class);
        return ResponseResult.okResult(mediaVo);
    }

    /**
     * 根据id查媒资播放地址
     * @param mediaId
     * @return
     */
    @Override
    public ResponseResult findMediaUrl(Long mediaId) throws Exception {
        Media media = this.getById(mediaId);
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(media.getFileId());
        String playURL = response.getPlayInfoList().get(0).getPlayURL();
        ResourceVo resourceVo=new ResourceVo();
        resourceVo.setPlayUrl(playURL);
        return ResponseResult.okResult(resourceVo);
    }
}
